// controllers/answerController.js
const { code } = require('three/tsl');
const { pool } = require('../config/db');

// 1. 获取所有回答（支持分页）
exports.getAllAnswers = async (req, res, next) => {
  try {
    const { page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;

    // 查回答列表（关联用户信息，显示“谁回答的”）
    const [answers] = await pool.query(
      `SELECT a.*, u.username, u.nickname, u.avatar, q.title as question_title
       FROM answers a
       JOIN users u ON a.user_id = u.id
       JOIN questions q ON a.question_id = q.id
       ORDER BY a.created_at DESC
       LIMIT ? OFFSET ?`,
      [parseInt(limit), parseInt(offset)]
    );

    // 查总数量（用于分页）
    const [countResult] = await pool.query('SELECT COUNT(*) as total FROM answers');
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      success: true,
      count: answers.length,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
      data: answers
    });
  } catch (err) {
    next(err);
  }
};

// 2. 按问题ID获取所有回答（核心：看某个问题的所有回答）
exports.getAnswersByQuestion = async (req, res, next) => {
  try {
    const { questionId } = req.params;
    const { page = 1, limit = 15 ,keyword='is_accepted'} = req.query;
    const offset = (page - 1) * limit;

    // 先检查问题是否存在
    const [questionExists] = await pool.query(
      'SELECT id FROM questions WHERE id = ?',
      [questionId]
    );
    if (questionExists.length === 0) {
      const error = new Error('对应的问题不存在');
      error.statusCode = 404;
      throw error;
    }

    // 查该问题的所有回答
    const [answers] = await pool.query(
      `SELECT answers.id , answers.content,answers.is_accepted,answers.like_count,answers.created_at,users.username,users.avatar
        FROM answers
        JOIN users ON answers.user_id = users.id
        WHERE answers.question_id = ?
        ORDER BY ?, like_count DESC, created_at DESC
        LIMIT ? OFFSET ?`,
      [questionId, keyword, parseInt(limit), parseInt(offset)]
    );

    // 查该问题的回答总数
    const [countResult] = await pool.query(
      'SELECT COUNT(*) as total FROM answers WHERE question_id = ?',
      [questionId]
    );
    const total = parseInt(countResult[0].total);

    res.status(200).json({
      code:200,
      msg:'回复获取失败',
      data: answers,
      total,
      totalPages: Math.ceil(total / limit),
      currentPage: parseInt(page),
    });
  } catch (err) {
    next(err);
  }
};

// 3. 提交新回答（回答问题，核心功能：回答后可赚积分）
exports.createAnswer = async (req, res, next) => {
  try {
    const { content, question_id, user_id } = req.body;

    // 验证必填字段（内容、问题ID、用户ID）
    if (!content || !question_id || !user_id) {
      const error = new Error('回答内容、问题ID、用户ID为必填项');
      error.statusCode = 400;
      throw error;
    }

    // 检查问题是否存在
    const [questionExists] = await pool.query(
      'SELECT id FROM questions WHERE id = ?',
      [question_id]
    );
    if (questionExists.length === 0) {
      const error = new Error('对应的问题不存在');
      error.statusCode = 404;
      throw error;
    }

    // 检查用户是否存在
    const [userExists] = await pool.query(
      'SELECT id FROM users WHERE id = ?',
      [user_id]
    );
    if (userExists.length === 0) {
      const error = new Error('用户不存在');
      error.statusCode = 404;
      throw error;
    }

    // 1. 插入回答数据
    const [answerResult] = await pool.query(
      `INSERT INTO answers 
       (content, question_id, user_id, created_at, updated_at) 
       VALUES (?, ?, ?, NOW(), NOW())`,
      [content, question_id, user_id]
    );

    // 2. 回答成功后，给用户加积分（核心规则：回答得积分）
    const POINTS_PER_ANSWER = 10; // 每回答一次得10积分（可自定义）
    await pool.query(
      'UPDATE users SET points = points + ?, updated_at = NOW() WHERE id = ?',
      [POINTS_PER_ANSWER, user_id]
    );

    // 3. 获取新创建的回答详情（返回给前端）
    const [newAnswer] = await pool.query(
      `SELECT a.*, u.username, u.nickname, u.avatar, q.title as question_title
       FROM answers a
       JOIN users u ON a.user_id = u.id
       JOIN questions q ON a.question_id = q.id
       WHERE a.id = ?`,
      [answerResult.insertId]
    );

    // 4. 获取用户更新后的积分（返回给前端，显示“积分+10”）
    const [updatedUser] = await pool.query(
      'SELECT points FROM users WHERE id = ?',
      [user_id]
    );

    res.status(201).json({
      success: true,
      message: `回答成功！获得 ${POINTS_PER_ANSWER} 积分`,
      data: {
        answer: newAnswer[0],
        currentPoints: updatedUser[0].points // 用户当前积分
      }
    });
  } catch (err) {
    next(err);
  }
};

// 4. 获取单个回答详情
exports.getAnswerById = async (req, res, next) => {
  try {
    const { id } = req.params;

    const [answers] = await pool.query(
      `SELECT a.*, u.username, u.nickname, u.avatar, q.title as question_title
       FROM answers a
       JOIN users u ON a.user_id = u.id
       JOIN questions q ON a.question_id = q.id
       WHERE a.id = ?`,
      [id]
    );

    if (answers.length === 0) {
      const error = new Error('未找到该回答');
      error.statusCode = 404;
      throw error;
    }

    res.status(200).json({
      success: true,
      data: answers[0]
    });
  } catch (err) {
    next(err);
  }
};

// 5. 删除回答（仅回答者本人可删，且删除后扣回积分）
exports.deleteAnswer = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { user_id } = req.body; // 操作人ID（需验证是否是回答者）

    // 1. 查回答是否存在，且获取回答者ID和关联的问题ID
    const [answers] = await pool.query(
      'SELECT id, user_id, question_id FROM answers WHERE id = ?',
      [id]
    );
    if (answers.length === 0) {
      const error = new Error('未找到该回答');
      error.statusCode = 404;
      throw error;
    }

    // 2. 验证权限：仅回答者本人可删
    const answerOwnerId = answers[0].user_id;
    if (parseInt(user_id) !== answerOwnerId) {
      const error = new Error('没有权限删除此回答（仅回答者可删）');
      error.statusCode = 403;
      throw error;
    }

    // 3. 删除回答
    await pool.query('DELETE FROM answers WHERE id = ?', [id]);

    // 4. 扣回积分（删除回答，收回之前给的积分）
    const POINTS_PER_ANSWER = 10;
    await pool.query(
      'UPDATE users SET points = points - ?, updated_at = NOW() WHERE id = ?',
      [POINTS_PER_ANSWER, user_id]
    );

    // 5. 获取用户更新后的积分
    const [updatedUser] = await pool.query(
      'SELECT points FROM users WHERE id = ?',
      [user_id]
    );

    res.status(200).json({
      success: true,
      message: `回答删除成功！扣除 ${POINTS_PER_ANSWER} 积分`,
      data: {
        currentPoints: updatedUser[0].points // 用户当前积分
      }
    });
  } catch (err) {
    next(err);
  }
};